package com.demo.core.dao;

import com.demo.base.model.company.CompanyInfo;
import com.demo.base.model.company.Score;
import com.demo.base.page.IPagableDTO;
import com.demo.base.page.PagableDTO;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

/**
 * Created by jiandandia on 2017/4/6.
 */
@Repository

public class CompanyInfoDao extends BaseDao {

    public CompanyInfo newOrupdateCompanyInfo(CompanyInfo companyInfo) throws Exception {
        return saveEntity(companyInfo);
    }

    public CompanyInfo getCompanyInfoById(String companyInfoId) throws Exception{
        CompanyInfo retval = null;
        try {
            if (!StringUtils.isEmpty(companyInfoId)) {
                retval = (CompanyInfo) this.get(CompanyInfo.class, companyInfoId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e);
        }
        return retval;
    }

    public IPagableDTO<CompanyInfo> getCompanyInfoByQuery(String companyName, IPagableDTO pagableDTO) {
        IPagableDTO<CompanyInfo> retval = new PagableDTO<CompanyInfo>();
        try {
            Session session = getSession();
            Criteria c = session.createCriteria(CompanyInfo.class);
            //根据公司名称来模糊查询
            if(!StringUtils.isEmpty(companyName)){
                c.add(Restrictions.like("companyName", "%"+companyName+"%"));
            }

            //后期加其他查询条件
            Long totalRow = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
            retval.setTotalRow(totalRow.intValue());
            c.setProjection(null);
            if (null != pagableDTO) {
                c.setFirstResult(pagableDTO.getStartRow());
                c.setFetchSize(pagableDTO.getPageSize());
                c.setMaxResults(pagableDTO.getPageSize());
            }
            retval.setData(c.list());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retval;
    }

    public void delteCompanyInfoById(String id) throws Exception{
        Session s = getSession();
        try {
            s.delete(s.get(CompanyInfo.class, id));
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e);
        }
    }

    public Score newCompanyInfoScore(Score score) throws Exception {
        return saveEntity(score);
    }
}
